package vip.idiy.anwei_android_iot;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.content.res.AppCompatResources;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import org.apache.commons.lang3.StringUtils;

import vip.idiy.anwei_android_iot.dialog.CustomDialog;
import vip.idiy.anwei_android_iot.domin.DeviceData;
import vip.idiy.anwei_android_iot.domin.DeviceInfo;
import vip.idiy.anwei_android_iot.utils.ActivityFactory;
import vip.idiy.anwei_android_iot.utils.DatabaseUtil;
import vip.idiy.anwei_android_iot.utils.IotUtil;
import vip.idiy.anwei_android_iot.utils.PermissionUtil;
import vip.idiy.anwei_android_iot.utils.SocketUtil;
import vip.idiy.anwei_android_iot.utils.ViewUtil;
import vip.idiy.anwei_android_iot.utils.dbHandle.DeviceDataHandle;
import vip.idiy.anwei_android_iot.utils.dbHandle.DeviceInfoHandle;
import vip.idiy.anwei_android_iot.views.LayoutBasicInfo;
import vip.idiy.anwei_android_iot.views.MsgHandler;
import vip.idiy.anwei_android_iot.views.MyImageButton;

public class AddEditDataActivity extends AppCompatActivity implements MsgHandler.MsgCallback {

    private final String TAG = "myTag " + " AddEditDataActivity ";

    private DeviceInfo deviceInfo;
    private DeviceData deviceData;

    private LinearLayout add_edit_data_container;
    private DeviceDataHandle deviceDataHandle;
    private LayoutBasicInfo layout_basic_device_id;


    private boolean result = false;
    private int mode;
    private LayoutBasicInfo layout_basic_data_wifi_name;
    private LayoutBasicInfo layout_basic_data_wifi_psw;
    private LayoutBasicInfo layout_basic_data_auto_wifi;
    private LayoutBasicInfo layout_basic_data_mqtt_server;
    private LayoutBasicInfo layout_basic_data_mqtt_port;
    private LayoutBasicInfo layout_basic_data_mqtt_name;
    private LayoutBasicInfo layout_basic_data_mqtt_psw;
    private LayoutBasicInfo layout_basic_data_mqtt_sub;
    private LayoutBasicInfo layout_basic_data_mqtt_pub;

    // 设备热点wifi
    private final String IOT_WIFI = "anwei-iot";

    private final String CONNECT_IP = "192.168.4.1";
    private final int CONNECT_PORT = 8080;

    private final String RECEIVE_SUCCESS = "success";

    private final int CONNECT_SUCCESS = 1001;
    private final int CONNECT_FAIL = 1002;
    private final int RECEIVE_DATA = 1003;


    private MsgHandler msgHandler;
    private SocketUtil socketUtil;
    private TextView add_edit_connect_device_status_text_view;
    private Button add_edit_data_connect_device_button;
    private DeviceInfoHandle deviceInfoHandle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_edit_data);
        // 设置设透明状态栏,导航栏. 状态栏字体修改为黑色
        ViewUtil.setViewStyle(this, true);
        // 设备运行信息
        deviceInfo = new DeviceInfo();
        // 设备数据
        deviceData = new DeviceData();

        DatabaseUtil databaseUtil = DatabaseUtil.getInstance(this);
        // 设备数据
        deviceDataHandle = new DeviceDataHandle(databaseUtil);
        // 设备运行信息
        deviceInfoHandle = new DeviceInfoHandle(databaseUtil);

        //初始化窗口
        initView();
        // 创建MsgHandler对象并将其作为参数传递给构造函数
        msgHandler = new MsgHandler(this);

        socketUtil = new SocketUtil();

        /**
         * 动态申请wifi权限,在后面需要用到获取当前连接wifi的名称, 自动连接wifi暂时搞不了
         */
        PermissionUtil.request(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                integer -> {
                    if (integer == PackageManager.PERMISSION_GRANTED) {

                    } else {
                        // 申请失败
                        Toast.makeText(this, "申请权限失败!", Toast.LENGTH_SHORT).show();
                    }
                });

    }

    /**
     * 初始化窗口
     */
    private void initView() {
        // 头部标题
        TextView layout_reuse_head_tv_title = findViewById(R.id.layout_reuse_head_tv_title);
        // 返回按钮
        findViewById(R.id.layout_reuse_head_return_myImageButton).setOnClickListener(v -> finish());

        TextView add_edit_data_hint = findViewById(R.id.add_edit_data_hint);
        add_edit_data_hint.setText(R.string.add_edit_data_hint);

        add_edit_connect_device_status_text_view = findViewById(R.id.add_edit_connect_device_status_text_view);

        // 判断模式
        Intent intent = getIntent();
        mode = intent.getIntExtra("mode", 0);
        String par = intent.getStringExtra("par");

        // 添加或编辑按钮
        MyImageButton add_edit_data_button = findViewById(R.id.add_edit_data_button);
        add_edit_data_button.setOnClickListener(v -> addAndEditSceneData(mode));

        // 取消按钮
        findViewById(R.id.cancel_data_button).setOnClickListener(v -> finish());

        // 连接设备按钮
        add_edit_data_connect_device_button = findViewById(R.id.add_edit_data_connect_device_button);
        add_edit_data_connect_device_button.setOnClickListener(v -> SocketHandle());

        // 根据模式设置按钮样式
        switch (mode) {
            case GlobalApplication.EDIT_MODE: // 编辑
                layout_reuse_head_tv_title.setText(R.string.title_edit_data);
                add_edit_data_button.setImageResource(R.mipmap.icon_edit_white);
                add_edit_data_button.setText(getString(R.string.data_edit));
                add_edit_data_button.setBackground(AppCompatResources.getDrawable(AddEditDataActivity.this, R.drawable.ripple_blue));
                break;

            case GlobalApplication.ADD_MODE: // 增加
                layout_reuse_head_tv_title.setText(R.string.title_add_data);
                add_edit_data_button.setImageResource(R.mipmap.icon_add_white);
                add_edit_data_button.setText(getString(R.string.data_add));

                break;
            case GlobalApplication.REMOVE_MODE:
                layout_reuse_head_tv_title.setText(R.string.title_remove_data);
                add_edit_data_button.setImageResource(R.mipmap.icon_remove_white);
                add_edit_data_button.setText(getString(R.string.data_remove));
                add_edit_data_button.setBackground(AppCompatResources.getDrawable(AddEditDataActivity.this, R.drawable.ripple_red));
                break;
        }
        // LinearLayout  View容器
        add_edit_data_container = findViewById(R.id.add_edit_data_container);
        // 设备ID
        layout_basic_device_id = new LayoutBasicInfo(this)
                .init(true, false, false, true, false, false)
                .setLeftText(getString(R.string.table_device_id))
                .setLineBackground(R.drawable.ripple_gray)
                .setLeftImg(R.mipmap.icon_device);
        // wifi名称
        layout_basic_data_wifi_name = new LayoutBasicInfo(this)
                .init(true, false, false, true, false, false)
                .setLeftText(getString(R.string.table_wifi_name))
                .setLineBackground(R.drawable.ripple_gray)
                .setLeftImg(R.mipmap.icon_wifi);
        // wifi密码
        layout_basic_data_wifi_psw = new LayoutBasicInfo(this)
                .init(true, false, false, true, false, false)
                .setLeftText(getString(R.string.table_wifi_psw))
                .setLineBackground(R.drawable.ripple_gray)
                .setLeftImg(R.mipmap.icon_password);

        // 是否自动连接wifi
        layout_basic_data_auto_wifi = new LayoutBasicInfo(this)
                .init(true, true, false, false, true, false)
                .setLeftText(getString(R.string.table_auto_wifi))
                .setLineBackground(R.drawable.ripple_gray)
                .setCentreContent(getString(R.string.please_select_auto_wifi))
                .setLeftImg(R.mipmap.icon_connect);
        // mqtt服务器
        layout_basic_data_mqtt_server = new LayoutBasicInfo(this)
                .init(true, false, false, true, false, false)
                .setLeftText(getString(R.string.table_mqtt_server))
                .setLineBackground(R.drawable.ripple_gray)
                .setLeftImg(R.mipmap.icon_server);
        // mqtt端口
        layout_basic_data_mqtt_port = new LayoutBasicInfo(this)
                .init(true, false, false, true, false, false)
                .setLeftText(getString(R.string.table_mqtt_port))
                .setLineBackground(R.drawable.ripple_gray)
                .setLeftImg(R.mipmap.icon_port);
        // mqtt账号
        layout_basic_data_mqtt_name = new LayoutBasicInfo(this)
                .init(true, false, false, true, false, false)
                .setLeftText(getString(R.string.table_mqtt_name))
                .setLineBackground(R.drawable.ripple_gray)
                .setLeftImg(R.mipmap.icon_name);
        // mqtt密码
        layout_basic_data_mqtt_psw = new LayoutBasicInfo(this)
                .init(true, false, false, true, false, false)
                .setLeftText(getString(R.string.table_mqtt_psw))
                .setLineBackground(R.drawable.ripple_gray)
                .setLeftImg(R.mipmap.icon_password);
        // mqtt订阅
        layout_basic_data_mqtt_sub = new LayoutBasicInfo(this)
                .init(true, false, false, true, false, false)
                .setLeftText(getString(R.string.table_mqtt_sub))
                .setLineBackground(R.drawable.ripple_gray)
                .setLeftImg(R.mipmap.icon_sub);
        // mqtt发布
        layout_basic_data_mqtt_pub = new LayoutBasicInfo(this)
                .init(true, false, false, true, false, false)
                .setLeftText(getString(R.string.table_mqtt_pub))
                .setLineBackground(R.drawable.ripple_gray)
                .setLeftImg(R.mipmap.icon_place);


        // 如果是编辑和删除模式, 先获取记录
        if (mode == GlobalApplication.EDIT_MODE || mode == GlobalApplication.REMOVE_MODE) {
            deviceData = deviceDataHandle.selectByDeviceId(par);
            // 设置编辑框显示文本
            layout_basic_device_id.setCentreEditContent(deviceData.getDeviceId());
            layout_basic_data_wifi_name.setCentreEditContent(deviceData.getWifiName());
            layout_basic_data_wifi_psw.setCentreEditContent(deviceData.getWifiPsw());
            layout_basic_data_auto_wifi.setSwitchStatus(deviceData.isAutoWiFi());
            layout_basic_data_mqtt_server.setCentreEditContent(deviceData.getMqttServer());
            layout_basic_data_mqtt_port.setCentreEditContent(String.valueOf(deviceData.getMqttPort()));
            layout_basic_data_mqtt_name.setCentreEditContent(deviceData.getMqttName());
            layout_basic_data_mqtt_psw.setCentreEditContent(deviceData.getMqttPsw());
            layout_basic_data_mqtt_sub.setCentreEditContent(deviceData.getMqttSub());
            layout_basic_data_mqtt_pub.setCentreEditContent(deviceData.getMqttPub());
        }
        add_edit_data_container.addView(layout_basic_device_id);
        add_edit_data_container.addView(layout_basic_data_wifi_name);
        add_edit_data_container.addView(layout_basic_data_wifi_psw);
        add_edit_data_container.addView(layout_basic_data_auto_wifi);
        add_edit_data_container.addView(layout_basic_data_mqtt_server);
        add_edit_data_container.addView(layout_basic_data_mqtt_port);
        add_edit_data_container.addView(layout_basic_data_mqtt_name);
        add_edit_data_container.addView(layout_basic_data_mqtt_psw);
        add_edit_data_container.addView(layout_basic_data_mqtt_sub);
        add_edit_data_container.addView(layout_basic_data_mqtt_pub);
    }

    /**
     * 连接处理
     */
    private void SocketHandle() {
        String ssid = IotUtil.getConnectedWifiSsid(AddEditDataActivity.this);
        if (StringUtils.isEmpty(ssid)) {
            Toast.makeText(this, R.string.error_please_connect_device_wifi, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!IOT_WIFI.equals(ssid)) {
            Toast.makeText(this, R.string.error_please_connect_device_wifi, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!socketUtil.isConnected()) {
            socketUtil.connect(CONNECT_IP, CONNECT_PORT, new SocketUtil.OnConnectListener() {
                @Override
                public void onConnectSuccess() {
                    // 连接成功
                    Message msg = new Message();
                    msg.what = CONNECT_SUCCESS;
                    msgHandler.sendMessage(msg);
                }

                @Override
                public void onConnectFail() {
                    // 连接失败
                    Message msg = new Message();
                    msg.what = CONNECT_FAIL;
                    msgHandler.sendMessage(msg);

                }
            });

            // 设备热点断开处理
            socketUtil.setOnWifiDisconnectedListener(() -> {
                setTextViewStatus(R.string.disconnect_wifi, R.color.red);
                add_edit_data_connect_device_button.setText(R.string.connect_device);
                add_edit_data_connect_device_button.setBackground(AppCompatResources.getDrawable(AddEditDataActivity.this, R.drawable.ripple_button_green));
            });

        } else {
            // 断开处理
            socketUtil.disconnect();
            setTextViewStatus(R.string.disconnect_socket, R.color.red);
            add_edit_data_connect_device_button.setText(R.string.connect_device);
            add_edit_data_connect_device_button.setBackground(AppCompatResources.getDrawable(AddEditDataActivity.this, R.drawable.ripple_button_green));
        }
    }

    /**
     * 读取数据
     */
    private void receiveData() {
        socketUtil.receive(data -> {
            Message msg = new Message();
            msg.what = RECEIVE_DATA;
            msg.obj = data.trim();
            msgHandler.sendMessage(msg);
        });
    }

    /**
     * 消息处理
     *
     * @param msg
     */
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case CONNECT_SUCCESS:
                // 连接成功
                setTextViewStatus(R.string.connect_success, R.color.grass_green);
                add_edit_data_connect_device_button.setText(R.string.disconnect_device);
                add_edit_data_connect_device_button.setBackground(AppCompatResources.getDrawable(AddEditDataActivity.this, R.drawable.ripple_button_red));
                receiveData();
                break;

            case CONNECT_FAIL:
                // 连接失败
                setTextViewStatus(R.string.connect_fail, R.color.red);
                break;
            case RECEIVE_DATA:
                receiveDataHandle(msg.obj.toString());
                break;
        }
    }

    /**
     * 设备发送的数据处理
     */
    private void receiveDataHandle(String str) {
        if (RECEIVE_SUCCESS.equals(str)) {
            switch (mode) {
                case GlobalApplication.ADD_MODE:
                    deviceDataHandle.insert(deviceData);
                    // 如果设备已存在,则不添加
                    if (!deviceInfoHandle.isExist(deviceData.getDeviceId())) {
                        // 设置初始数据
                        deviceInfo.setDeviceId(deviceData.getDeviceId());
                        // 设置默认类型
                        deviceInfo.setTypeId(1);
                        // 设置默认位置
                        deviceInfo.setSceneId(1);
                        // 设置离线wifi信号
                        deviceInfo.setRssi(-101);
                        deviceInfoHandle.insert(deviceInfo);
                    }
                    break;
                case GlobalApplication.EDIT_MODE:
                    deviceDataHandle.update(deviceData);
                    break;
            }
            finish();
            return;
        }
        DeviceData data = IotUtil.analysisResult(str, DeviceData.class);
        layout_basic_device_id.setCentreEditContent(data.getDeviceId());
        layout_basic_data_wifi_name.setCentreEditContent(data.getWifiName());
        layout_basic_data_wifi_psw.setCentreEditContent(data.getWifiPsw());
        layout_basic_data_auto_wifi.setSwitchStatus(data.isAutoWiFi());
        layout_basic_data_mqtt_server.setCentreEditContent(data.getMqttServer());
        layout_basic_data_mqtt_port.setCentreEditContent(String.valueOf(data.getMqttPort()));
        layout_basic_data_mqtt_name.setCentreEditContent(data.getMqttName());
        layout_basic_data_mqtt_psw.setCentreEditContent(data.getMqttPsw());
        layout_basic_data_mqtt_sub.setCentreEditContent(data.getMqttSub());
        layout_basic_data_mqtt_pub.setCentreEditContent(data.getMqttPub());
    }

    /**
     * 设置连接状态
     *
     * @param text
     * @param color
     */
    private void setTextViewStatus(int text, int color) {
        add_edit_connect_device_status_text_view.setText(text);
        add_edit_connect_device_status_text_view.setTextColor(getResources().getColor(color, null));
    }

    /**
     * 添加或编辑, 删除不用连接
     *
     * @param mode
     */
    private void addAndEditSceneData(int mode) {

        if (mode == GlobalApplication.ADD_MODE || mode == GlobalApplication.EDIT_MODE) {
            if (!socketUtil.isConnected()) {
                Toast.makeText(this, R.string.error_please_connect_device_wifi, Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (layout_basic_device_id.getCentreEditContent() != null && !layout_basic_device_id.getCentreEditContent().isEmpty()) {
            deviceData.setDeviceId(layout_basic_device_id.getCentreEditContent());
        }
        if (layout_basic_data_wifi_name.getCentreEditContent() != null && !layout_basic_data_wifi_name.getCentreEditContent().isEmpty()) {
            deviceData.setWifiName(layout_basic_data_wifi_name.getCentreEditContent());
        }
        if (layout_basic_data_wifi_psw.getCentreEditContent() != null && !layout_basic_data_wifi_psw.getCentreEditContent().isEmpty()) {
            deviceData.setWifiPsw(layout_basic_data_wifi_psw.getCentreEditContent());
        }
        // 开关状态
        deviceData.setAutoWiFi(layout_basic_data_auto_wifi.getSwitchStatus());

        if (layout_basic_data_mqtt_server.getCentreEditContent() != null && !layout_basic_data_mqtt_server.getCentreEditContent().isEmpty()) {
            deviceData.setMqttServer(layout_basic_data_mqtt_server.getCentreEditContent());
        }
        if (layout_basic_data_mqtt_port.getCentreEditContent() != null && !layout_basic_data_mqtt_port.getCentreEditContent().isEmpty()) {
            deviceData.setMqttPort(Integer.parseInt(layout_basic_data_mqtt_port.getCentreEditContent()));
        }
        if (layout_basic_data_mqtt_name.getCentreEditContent() != null && !layout_basic_data_mqtt_name.getCentreEditContent().isEmpty()) {
            deviceData.setMqttName(layout_basic_data_mqtt_name.getCentreEditContent());
        }
        if (layout_basic_data_mqtt_psw.getCentreEditContent() != null && !layout_basic_data_mqtt_psw.getCentreEditContent().isEmpty()) {
            deviceData.setMqttPsw(layout_basic_data_mqtt_psw.getCentreEditContent());
        }
        if (layout_basic_data_mqtt_sub.getCentreEditContent() != null && !layout_basic_data_mqtt_sub.getCentreEditContent().isEmpty()) {
            deviceData.setMqttSub(layout_basic_data_mqtt_sub.getCentreEditContent());
        }
        if (layout_basic_data_mqtt_pub.getCentreEditContent() != null && !layout_basic_data_mqtt_pub.getCentreEditContent().isEmpty()) {
            deviceData.setMqttPub(layout_basic_data_mqtt_pub.getCentreEditContent());
        }
        // 判断是否有空数据
        if (!deviceData.checkEmpty()) {
            Toast.makeText(this, R.string.error_please_input_full_data, Toast.LENGTH_SHORT).show();
            return;
        }
        // 如果是增加模式, 判断数据是否存在
        if (mode == GlobalApplication.ADD_MODE) {
            if (deviceDataHandle.isExist(deviceData.getDeviceId())) {
                Toast.makeText(this, R.string.data_is_exist, Toast.LENGTH_SHORT).show();
                return;
            }
        }
        switch (mode) {
            case GlobalApplication.EDIT_MODE: // 编辑
            case GlobalApplication.ADD_MODE: // 添加
                sendDataToDevice(JSON.toJSONString(deviceData));
                break;
            case GlobalApplication.REMOVE_MODE: // 删除
                CustomDialog customDialog = new CustomDialog(AddEditDataActivity.this, new CustomDialog.CustomDialogClickListener() {
                    @Override
                    public void doConfirm() {
                        if (deviceInfoHandle.isExist(deviceData.getDeviceId())) {
                            DeviceInfo info = deviceInfoHandle.selectByDeviceId(deviceData.getDeviceId());
                            deviceInfoHandle.delete(info);
                        }
                        if (deviceDataHandle.isExist(deviceData.getDeviceId())) {
                            deviceDataHandle.delete(deviceData);
                            finish();
                        }
                    }

                    @Override
                    public void doCancel() {

                    }
                });
                customDialog.setMessage(getString(R.string.dialog_title_device_remove));
                customDialog.setMessage(getString(R.string.dialog_msg_is_remove_data, deviceData.getDeviceId()));
                customDialog.show();
                break;
        }
    }

    /**
     * 发送数据到设备
     *
     * @param data
     */
    private void sendDataToDevice(String data) {
        // 需在线程发送
        Thread sendThread = new Thread(() -> {
            synchronized (socketUtil) {
                socketUtil.send(data);
            }
        });
        sendThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 断开socket连接
        if (socketUtil.isConnected()) {
            socketUtil.disconnect();
        }
        // 关闭后刷新数据
        ActivityFactory.deviceHandleActivity_flushList(mode);
    }


}